package com.cms.controllers;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cms.entity.Admin;
import com.cms.entity.Role;
import com.cms.service.AdminService;
import com.cms.service.RoleService;
import com.cms.support.Result;

/**
 * @ClassName: AdminController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhangp
 * @date 2016年3月31日 下午2:48:12
 * 
 */
@Controller
public class AdminController {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(AdminController.class);

	@Autowired
	private AdminService userService;
	@Autowired
	private RoleService roleService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Role.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				Integer id = Integer.parseInt(text);
				setValue(roleService.getRole(id));
			}
		});
	}

	@ModelAttribute
	public void loadRoles(Model model) {
		model.addAttribute("roles",
				roleService.listDateRoles(null, null, null, 1000));
	}

	/**
	 * @Title: index
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping("admin")
	public String index(Model model) {
		return "admin/index";
	}

	/**
	 * @Title: list
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param userName
	 * @param realname
	 * @param model
	 * @param iDisplayLength
	 * @param iDisplayStart
	 * @param sEcho
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("admin/list")
	public Object list(String userName, String realname, Model model,
			Integer iDisplayLength, Integer iDisplayStart, Integer sEcho) {
		try {
			// 减去的是admin，该数据不能操作
			Long totalCount = userService.getCount(userName, realname) - 1;
			List<Admin> list = userService.listDateUsers(userName, realname,
					iDisplayStart, iDisplayLength);
			JSONObject getObj = new JSONObject();
			getObj.put("sEcho", sEcho);// 不知道这个值有什么用,有知道的请告知一下
			getObj.put("iTotalRecords", totalCount);// 实际的行数
			getObj.put("iTotalDisplayRecords", totalCount);// 显示的行数,这个要和上面写的一样
			getObj.put("aaData", list);// 要以JSON格式返回
			return getObj;
		} catch (Exception e) {
			LOGGER.error("UserCardController 查询用户错误,", e);
			return null;
		}
	}

	/**
	 * @Title: add
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "admin/add", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("user", new Admin());
		return "admin/add";
	}

	/**
	 * @Title: doAdd
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param user
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/add", method = RequestMethod.POST)
	public Object doAdd(Admin user) {
		try {
			user.setEnabled(true);
			user.setStatus(0);
			userService.createUser(user);
		} catch (Exception e) {
			LOGGER.error("UserCardController 添加用户错误,", e);
			return new Result(false, "系统异常");
		}

		return new Result();
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "admin/modify", method = RequestMethod.GET)
	public String modify(Model model, @RequestParam String id) {
		model.addAttribute("user", userService.loadUserByUsername(id));
		return "admin/modify";
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param user
	 * @param request
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/modify", method = RequestMethod.POST)
	public Object modify(Admin user, HttpServletRequest request) {
		try {
			Admin oldUser = userService.loadUser(user.getUsername());
			if (oldUser != null) {
				oldUser.setDepartment(user.getDepartment());
				oldUser.setRealname(user.getRealname());
				oldUser.setAuthorities(user.getAuthorities());
			} else {
				LOGGER.error("UserCardController 修改用户信息错误, 用户不存在：",
						user.getUsername());
				return new Result(false, "记录不存在，请刷新列表再操作！");
			}
			userService.updateUser(oldUser);
		} catch (Exception e) {
			LOGGER.error("UserCardController 修改用户信息错误", e);
			return new Result(false, "系统异常");
		}

		return new Result();
	}

	/**
	 * @Title: modifyPass
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "admin/modifyPass", method = RequestMethod.GET)
	public String modifyPass() {
		return "modifyPwd";
	}

	/**
	 * @Title: modifyPass
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param password
	 * @param newPass
	 * @param request
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/modifyPass", method = RequestMethod.POST)
	public Object modifyPass(String password, String newPass,
			HttpServletRequest request) {
		HttpSession session = request.getSession();
		Result result = new Result(false, "系统错误！");
		MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder(
				"md5");
		password = encoder.encodePassword(password, null);
		Admin thisUser = new Admin();
		try {
			if (StringUtils.isBlank(password)) {
				return new Result(false, "密码不能为空");
			}
			if (StringUtils.isBlank(newPass)) {
				return new Result(false, "新密码不能为空");
			}
			if (password.equals(encoder.encodePassword(newPass, null))) {
				return new Result(false, "新密码不能与旧密码相同");
			}
			thisUser = (Admin) userService.loadUserByUsername(session
					.getAttribute("username").toString());
			if (thisUser.getPassword().equals(password)) {
				thisUser.setLastModifyPsdDate(new Date());
				thisUser.setPassword(encoder.encodePassword(newPass, null));
				userService.updateUser(thisUser);
				result.setObj("* 修改成功！");
				result.setSuccess(true);
				session.invalidate();
			} else {
				result.setSuccess(false);
				result.setObj("* 密码错误！");
			}
		} catch (Exception e) {
			LOGGER.error("用户修改密码异常", e);
		}
		return result;
	}

	/**
	 * @Title: information
	 * @Description: TODO(获取当前登录的用户的信息)
	 * @param model
	 * @param request
	 * @return Object
	 * @throws
	 */
	@RequestMapping(value = "admin/information")
	public Object information(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		try {
			model.addAttribute(
					"thisUser",
					userService.loadUserByUsername(session.getAttribute(
							"username").toString()));
		} catch (Exception e) {
			LOGGER.error("查看用户信息异常", e);
		}
		return "admin/information";
	}

	/**
	 * @Title: delete
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/delete")
	public Object delete(Model model, @RequestParam String id) {
		try {
			userService.removeById(id);
		} catch (Exception e) {
			LOGGER.error("删除用户异常", e);
			return new Result(false, "系统异常");
		}
		return new Result();
	}

	/**
	 * @Title: unlock
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/unlock", method = RequestMethod.POST)
	public Object unlock(Model model, @RequestParam String id) {
		Result result = new Result(false, "系统错误！");
		try {
			Admin user = userService.loadUser(id);
			user.setStatus(0);
			userService.updateUser(user);
			result.setSuccess(true);
			result.setObj("解冻用户成功！");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setObj("解冻用户失败！");
			LOGGER.error("解冻用户" + e);
		}
		return result;
	}

	/**
	 * @Title: restPwd
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "admin/restPwd", method = RequestMethod.POST)
	public Object restPwd(Model model, @RequestParam String id) {
		Result result = new Result(false, "系统错误！");
		try {
			Admin user = userService.loadUser(id);
			MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder(
					"md5");
			String password = encoder.encodePassword("CMS#123", null);
			user.setPassword(password);
			user.setLastModifyPsdDate(null);
			userService.updateUser(user);
			result.setSuccess(true);
			result.setObj("密码已重置为CMS#123，请登录修改密码！");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setObj("密码重置失败，请重试！");
			LOGGER.error("密码重置" + e);
		}
		return result;
	}

}
